/*
 * ShopDetailFragment.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.shopdetail;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.BaseFragment;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.data.model.ShopModel;
import com.yidiandao.business.manager.ImageManager;
import com.yidiandao.business.ui.adapter.ShopDetailPagerAdapter;
import com.yidiandao.business.ui.shopdetail.allgoods.ShopAllGoodsFragment;
import com.yidiandao.business.ui.shopdetail.allgoods.ShopAllGoodsPresenter;
import com.yidiandao.business.ui.shopdetail.category.ShopCategoryFragment;
import com.yidiandao.business.ui.shopdetail.category.ShopCategoryPresenter;
import com.yidiandao.business.ui.shopdetail.info.ShopInfoFragment;
import com.yidiandao.business.ui.shopdetail.info.ShopInfoPresenter;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.PriceUtils;
import com.yidiandao.business.utils.UIUtils;

import java.util.List;

/** 店铺详情页 - View */
public class ShopDetailFragment extends BaseFragment
        implements ShopDetailContract.View, View.OnClickListener {

    private static final String TAG = ShopDetailFragment.class.getSimpleName();

    private ShopDetailContract.Presenter mPresenter;

    private ImageView mIvShopAdImage;

    private ImageView mIvShopImage;

    private TextView mTvShopName;

    private TextView mTvShopDetail;

    private TextView mTvShopCollect;

    private TextView mTvQuality;

    private TextView mTvService;

    private TextView mTvLogistics;

    private ImageButton mIbtnBack;

    private TextView mTvTitle;

    private TabLayout mTabLayout;

    private ViewPager mViewPager;

    private ShopDetailPagerAdapter mPagerAdapter;

    private ShopCategoryFragment mShopCategoryFragment;

    private ShopAllGoodsFragment mShopAllGoodsFragment;

    private ShopInfoFragment mShopInfoFragment;

    private LinearLayout mLlShopDetail;

    private TextView mTvNotice;

    private ImageView mIvCloseNotice;

    private RelativeLayout mRlytNotice;

    private Toolbar mToolbar;

    private AppBarLayout mAppbarLayout;

    private LinearLayout mLlCollect;

    private ImageView mIvCollect;

    private int scrollHeight;

    public static ShopDetailFragment getInstance(Bundle bundle) {
        ShopDetailFragment fragment = new ShopDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void initViews() {
        mIvShopAdImage = (ImageView) mRootView.findViewById(R.id.iv_shop_ad_image);
        mIvShopImage = (ImageView) mRootView.findViewById(R.id.iv_shop_info_image);
        mTvShopName = (TextView) mRootView.findViewById(R.id.tv_shop_name);
        mTvShopDetail = (TextView) mRootView.findViewById(R.id.tv_shop_detail);
        mTvShopCollect = (TextView) mRootView.findViewById(R.id.tv_shop_collect);
        mTvQuality = (TextView) mRootView.findViewById(R.id.tv_quality);
        mTvService = (TextView) mRootView.findViewById(R.id.tv_service);
        mTvLogistics = (TextView) mRootView.findViewById(R.id.tv_logistics);
        mIbtnBack = (ImageButton) mRootView.findViewById(R.id.ibtn_back);
        mTvTitle = (TextView) mRootView.findViewById(R.id.tv_title);
        mTvNotice = (TextView) mRootView.findViewById(R.id.tv_notice);
        mIvCloseNotice = (ImageView) mRootView.findViewById(R.id.iv_close_notice);
        mRlytNotice = (RelativeLayout) mRootView.findViewById(R.id.rlyt_notice);
        mTabLayout = (TabLayout) mRootView.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) mRootView.findViewById(R.id.viewpager);

        mLlCollect = (LinearLayout) mRootView.findViewById(R.id.ll_collect);
        mIvCollect = (ImageView) mRootView.findViewById(R.id.iv_collect);
        mAppbarLayout = (AppBarLayout) mRootView.findViewById(R.id.appbar_layout);
        mLlShopDetail = (LinearLayout) mRootView.findViewById(R.id.ll_shop_detail);
        mToolbar = (Toolbar) mRootView.findViewById(R.id.toolbar);
        mIbtnBack.setOnClickListener(this);
        mLlCollect.setOnClickListener(this);

        initListeners();
        initViewPager();
        initPresenter();
        initShopHeaderState();

        // 显示顶部信息
        mPresenter.loadHeader(getArguments());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            // 低内存回收
            restoreAllTabs();
        }
    }

    private void restoreAllTabs() {
        FragmentManager fragmentManager = getChildFragmentManager();
        mPagerAdapter = new ShopDetailPagerAdapter(fragmentManager);

        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment instanceof ShopCategoryFragment) {
                mShopCategoryFragment = (ShopCategoryFragment) fragment;
            } else if (fragment instanceof ShopAllGoodsFragment) {
                mShopAllGoodsFragment = (ShopAllGoodsFragment) fragment;
            } else if (fragment instanceof ShopInfoFragment) {
                mShopInfoFragment = (ShopInfoFragment) fragment;
            }
        }

        initFragments();
    }

    private void initListeners() {
        mIvCloseNotice.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setShopNoticeVisibility(false);
                    }
                });
    }

    private void initShopHeaderState() {
        mLlShopDetail
                .getViewTreeObserver()
                .addOnGlobalLayoutListener(
                        new ViewTreeObserver.OnGlobalLayoutListener() {
                            @Override
                            public void onGlobalLayout() {
                                scrollHeight = mLlShopDetail.getHeight() - mToolbar.getHeight();
                                mLlShopDetail
                                        .getViewTreeObserver()
                                        .removeGlobalOnLayoutListener(this);
                            }
                        });
        mAppbarLayout.addOnOffsetChangedListener(
                new AppBarLayout.OnOffsetChangedListener() {
                    @Override
                    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                        int alpha;
                        if (verticalOffset != 0) {
                            alpha = -verticalOffset * 255 / scrollHeight;
                        } else {
                            alpha = 0;
                        }
                        if (alpha > 255) alpha = 255;
                        mToolbar.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
                        mTvTitle.setTextColor(Color.argb(alpha, 63, 38, 49));
                    }
                });
    }

    @Override
    public void setShopNoticeVisibility(boolean visibility) {
        mRlytNotice.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }

    private void initViewPager() {
        if (mPagerAdapter == null) {
            String supplierId = getArguments().getString(Intents.EXTRA_SUPPLIER_ID);
            // 添加三个页面
            mShopCategoryFragment = ShopCategoryFragment.getInstance(supplierId);
            mShopAllGoodsFragment = ShopAllGoodsFragment.getInstance(supplierId);
            mShopInfoFragment = ShopInfoFragment.getInstance(supplierId);

            mPagerAdapter = new ShopDetailPagerAdapter(getChildFragmentManager());

            initFragments();
        }
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(1);

        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void initFragments() {
        mPagerAdapter.addFragment(mShopCategoryFragment);
        mPagerAdapter.addFragment(mShopAllGoodsFragment);
        mPagerAdapter.addFragment(mShopInfoFragment);
    }

    private void initPresenter() {
        new ShopCategoryPresenter((ShopCategoryFragment) mPagerAdapter.getItem(0), new ShopModel());
        new ShopAllGoodsPresenter((ShopAllGoodsFragment) mPagerAdapter.getItem(1), new ShopModel());
        new ShopInfoPresenter((ShopInfoFragment) mPagerAdapter.getItem(2), new ShopModel());
    }

    @Override
    public void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            mTvTitle.setText(title);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shop_detail;
    }

    @Override
    public void setPresenter(ShopDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void setQualityLevel(float level) {
        PriceUtils.setShopValueChange(mTvQuality, level);
    }

    @Override
    public void setServiceLevel(float level) {
        PriceUtils.setShopValueChange(mTvService, level);
    }

    @Override
    public void setLogisticsLevel(float level) {
        PriceUtils.setShopValueChange(mTvLogistics, level);
    }

    @Override
    public void setHasCollection(boolean hasCollection) {
        mTvShopCollect.setText(
                UIUtils.getString(
                        hasCollection ? R.string.shop_cancel_collect : R.string.shop_collect));
        mIvCollect.setImageResource(
                hasCollection ? R.mipmap.ic_collect : R.mipmap.ic_collect_empty);
    }

    @Override
    public void refreshShopName(String shopName) {
        mTvTitle.setText(shopName);
        mTvShopName.setText(shopName);
    }

    @Override
    public void refreshShopHeader(
            String shopLogo, String bigImage, int goodsNumber, int saleNumber, String shopNotice) {
        ImageLoader.loadShopLogo(mActivity, mIvShopImage, shopLogo);
        ImageLoader.loadShopADImage(mActivity, mIvShopAdImage, bigImage);

        mTvShopDetail.setText(
                UIUtils.getString(R.string.shop_sales_count, goodsNumber));

        // 店铺公告
        boolean emptyShopNotice = TextUtils.isEmpty(shopNotice);
        setShopNoticeVisibility(!emptyShopNotice);
        if (!emptyShopNotice) {
            mTvNotice.requestFocus();
            mTvNotice.requestFocusFromTouch();
            mTvNotice.setText(shopNotice);
        }
    }

    @Override
    public String getPagerTag() {
        return TAG;
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_back:
                mActivity.finish();
                break;
            case R.id.ll_collect:
                mPresenter.collectShop();
                break;
        }
    }

    @Override
    public void onDestroy() {
        ImageManager.getInstance().clearList();
        super.onDestroy();
    }
}
